<template>
  <view class="post-card" @click="handleClick">
    <!-- 用户信息 -->
    <view class="card-header">
      <view class="user-info">
        <u-avatar :src="post.userInfo?.avatar" size="36"></u-avatar>
        <view class="user-details">
          <text class="nickname">{{ post.userInfo?.nickname }}</text>
          <text class="time">{{ formatRelativeTime(post.createdAt) }}</text>
        </view>
      </view>
      <view class="category-tag">
        <text>{{ post.categoryInfo?.name }}</text>
      </view>
    </view>

    <!-- 内容 -->
    <view class="card-content">
      <text v-if="post.title" class="title">{{ post.title }}</text>
      <text class="content text-ellipsis-3">{{ post.content }}</text>
    </view>

    <!-- 媒体内容 -->
    <view v-if="post.mediaUrls && post.mediaUrls.length > 0" class="media-container">
      <view v-if="post.mediaType === 'image'" class="image-grid">
        <image
          v-for="(url, index) in post.mediaUrls.slice(0, 3)"
          :key="index"
          :src="url"
          class="media-image"
          mode="aspectFill"
          @click.stop="previewImages(index)"
        />
      </view>
      <view v-else-if="post.mediaType === 'video'" class="video-container">
        <video
          :src="post.mediaUrls[0]"
          class="media-video"
          :poster="post.mediaUrls[0] + '?x-oss-process=video/snapshot,t_1000'"
          :show-center-play-btn="true"
          @click.stop
        />
      </view>
    </view>

    <!-- 价格信息 -->
    <view v-if="post.priceInfo" class="price-info">
      <text class="price">¥{{ post.priceInfo.price }}</text>
      <text v-if="post.priceInfo.unit" class="unit">/{{ post.priceInfo.unit }}</text>
      <text v-if="post.priceInfo.negotiable" class="negotiable">可议价</text>
    </view>

    <!-- 底部信息 -->
    <view class="card-footer">
      <view class="location">
        <u-icon name="map" size="16" color="#999"></u-icon>
        <text class="ml-xs">{{ formatLocationText }}</text>
      </view>
      <view class="actions">
        <view class="action-item" @click.stop="handleLike">
          <u-icon
            :name="post.isLiked ? 'heart-fill' : 'heart'"
            size="18"
            :color="post.isLiked ? '#fa3534' : '#999'"
          ></u-icon>
          <text class="action-text">{{ formatNumber(post.likeCount) }}</text>
        </view>
        <view class="action-item" @click.stop="handleCollect">
          <u-icon
            :name="post.isCollected ? 'star-fill' : 'star'"
            size="18"
            :color="post.isCollected ? '#ff9900' : '#999'"
          ></u-icon>
          <text class="action-text">收藏</text>
        </view>
        <view class="action-item" @click.stop="handleContact">
          <u-icon name="chat" size="18" color="#999"></u-icon>
          <text class="action-text">联系</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed, defineProps, defineEmits } from 'vue'
import type { Post } from '@/types'
import { formatRelativeTime, formatDistance, formatNumber } from '@/utils/format'
import { previewImage } from '@/utils/common'
import { postApi } from '@/api'

// Props
const props = defineProps<{
  post: Post
}>()

// Emits
const emit = defineEmits<{
  (e: 'click'): void
}>()

// 计算属性
const formatLocationText = computed(() => {
  if (!props.post.locationInfo) return '未知'

  const { address, distance } = props.post.locationInfo as any

  if (distance !== undefined) {
    return `距您约${formatDistance(distance)}`
  }

  return address || '未知'
})

/**
 * 点击卡片
 */
const handleClick = () => {
  emit('click')
}

/**
 * 预览图片
 */
const previewImages = (currentIndex: number) => {
  if (props.post.mediaUrls) {
    previewImage(props.post.mediaUrls, currentIndex)
  }
}

/**
 * 点赞
 */
const handleLike = async () => {
  try {
    if (props.post.isLiked) {
      await postApi.unlike(props.post.id)
      props.post.isLiked = false
      props.post.likeCount--
    } else {
      await postApi.like(props.post.id)
      props.post.isLiked = true
      props.post.likeCount++
    }
  } catch (err) {
    console.error('点赞失败:', err)
  }
}

/**
 * 收藏
 */
const handleCollect = async () => {
  try {
    if (props.post.isCollected) {
      await postApi.unfavorite(props.post.id)
      props.post.isCollected = false
      props.post.collectCount--
      uni.showToast({ title: '已取消收藏', icon: 'none' })
    } else {
      await postApi.favorite(props.post.id)
      props.post.isCollected = true
      props.post.collectCount++
      uni.showToast({ title: '收藏成功', icon: 'success' })
    }
  } catch (err) {
    console.error('收藏失败:', err)
  }
}

/**
 * 联系
 */
const handleContact = () => {
  // 跳转到聊天页面
  uni.navigateTo({
    url: `/pages/chat/detail?userId=${props.post.userId}&postId=${props.post.id}`
  })
}
</script>

<style lang="scss" scoped>
.post-card {
  background-color: var(--bg-color);
  border-radius: var(--radius-md);
  padding: var(--spacing-md);
  margin-bottom: var(--spacing-md);
  box-shadow: var(--shadow-sm);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: var(--spacing-md);

  .user-info {
    display: flex;
    align-items: center;

    .user-details {
      margin-left: var(--spacing-sm);
      display: flex;
      flex-direction: column;

      .nickname {
        font-size: 28rpx;
        color: var(--text-color);
        font-weight: 500;
      }

      .time {
        font-size: 24rpx;
        color: var(--text-color-placeholder);
        margin-top: 4rpx;
      }
    }
  }

  .category-tag {
    padding: 8rpx 16rpx;
    background-color: var(--primary-color);
    color: #ffffff;
    font-size: 24rpx;
    border-radius: var(--radius-sm);
  }
}

.card-content {
  .title {
    display: block;
    font-size: 32rpx;
    font-weight: 500;
    color: var(--text-color);
    margin-bottom: var(--spacing-sm);
  }

  .content {
    font-size: 28rpx;
    color: var(--text-color-secondary);
    line-height: 1.6;
  }
}

.media-container {
  margin-top: var(--spacing-md);

  .image-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 12rpx;

    .media-image {
      width: 220rpx;
      height: 220rpx;
      border-radius: var(--radius-sm);
    }
  }

  .video-container {
    .media-video {
      width: 100%;
      height: 400rpx;
      border-radius: var(--radius-md);
    }
  }
}

.price-info {
  display: flex;
  align-items: baseline;
  margin-top: var(--spacing-md);

  .price {
    font-size: 36rpx;
    font-weight: bold;
    color: var(--error-color);
  }

  .unit {
    font-size: 24rpx;
    color: var(--text-color-secondary);
    margin-left: 8rpx;
  }

  .negotiable {
    font-size: 24rpx;
    color: var(--warning-color);
    margin-left: var(--spacing-sm);
    padding: 4rpx 8rpx;
    background-color: rgba(255, 153, 0, 0.1);
    border-radius: 4rpx;
  }
}

.card-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: var(--spacing-md);
  padding-top: var(--spacing-sm);
  border-top: 1rpx solid var(--border-color-lighter);

  .location {
    display: flex;
    align-items: center;
    font-size: 24rpx;
    color: var(--text-color-placeholder);
  }

  .actions {
    display: flex;
    align-items: center;
    gap: var(--spacing-md);

    .action-item {
      display: flex;
      align-items: center;
      gap: 8rpx;

      .action-text {
        font-size: 24rpx;
        color: var(--text-color-placeholder);
      }
    }
  }
}
</style>
